package com.ponhu.ea2.stockcenter.provider.service.entity.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ponhu.ea2.stockcenter.provider.constants.CommonConstant;
import com.ponhu.ea2.stockcenter.provider.entity.StockInventoryWarehouseTrace;
import com.ponhu.ea2.stockcenter.provider.mapper.StockInventoryWarehouseTraceMapper;
import com.ponhu.ea2.stockcenter.provider.service.entity.StockInventoryWarehouseTraceService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ponhu.ea2.stockcenter.provider.support.service.RedisSupportService;
import com.ponhu.ea2.stockcenter.provider.utils.RedisUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * WMS任务链执行时货品在仓库间变动记录表 服务实现类
 *
 * @author ${author}
 * @since 2021-10-26
 */
@Service
public class StockInventoryWarehouseTraceServiceImpl
        extends ServiceImpl<StockInventoryWarehouseTraceMapper, StockInventoryWarehouseTrace>
        implements StockInventoryWarehouseTraceService {

    @Autowired
    private RedisSupportService redisSupportService;

    /**
     * 查询指定业务单号和指定货品的所有链路占用记录集合
     *
     * @param docNo
     * @param inventoryCodes
     * @return
     */
    @Override
    public List<StockInventoryWarehouseTrace> getWarehouseTraces(String docNo, Collection<String> inventoryCodes) {

        return getWarehouseTraces(docNo, inventoryCodes, null, null, null);
    }

    /**
     * 根据条件查询所有链路占用记录集合
     *
     * @param docNo
     * @param inventoryCodes
     * @param warehouseCode
     * @param inOccupy
     * @param inProgress
     * @return
     */
    @Override
    public List<StockInventoryWarehouseTrace> getWarehouseTraces(String docNo, Collection<String> inventoryCodes,
                                                                 String warehouseCode, Boolean inOccupy, Boolean inProgress) {

        LambdaQueryWrapper<StockInventoryWarehouseTrace> queryWrapper = Wrappers
                .lambdaQuery(StockInventoryWarehouseTrace.class)
                .in(StockInventoryWarehouseTrace::getInventoryCode, inventoryCodes);

        if (StringUtils.isNotEmpty(docNo))
            queryWrapper.eq(StockInventoryWarehouseTrace::getDirectSn, docNo);

        if (ObjectUtils.isNotEmpty(warehouseCode))
            queryWrapper.eq(StockInventoryWarehouseTrace::getWarehouseCode, warehouseCode);

        if (ObjectUtils.isNotEmpty(inOccupy))
            queryWrapper.eq(StockInventoryWarehouseTrace::getInOccupy, inOccupy);

        if (ObjectUtils.isNotEmpty(inProgress))
            queryWrapper.eq(StockInventoryWarehouseTrace::getInProgress, inProgress);

        return list(queryWrapper);
    }

    /**
     * 查询对应货品在指定仓库排除指定业务单号外的全部链路占用库存数【MAP：key-货品编码，value-链路占用库存数】
     *
     * @param docNo
     * @param inventoryCodes
     * @param warehouseCode
     * @return
     */
    @Override
    public Map<String, Integer> getAllTracesOccupyExcludeToMap(String docNo,
                                                               Collection<String> inventoryCodes, String warehouseCode) {

        LambdaQueryWrapper<StockInventoryWarehouseTrace> queryWrapper = Wrappers
                .lambdaQuery(StockInventoryWarehouseTrace.class)
                .ne(StockInventoryWarehouseTrace::getDirectSn, docNo)
                .in(StockInventoryWarehouseTrace::getInventoryCode, inventoryCodes)
                .eq(StockInventoryWarehouseTrace::getWarehouseCode, warehouseCode)
                .eq(StockInventoryWarehouseTrace::getInOccupy, true)
                .eq(StockInventoryWarehouseTrace::getInProgress, true);

        return list(queryWrapper).stream().collect(Collectors
                .groupingBy(StockInventoryWarehouseTrace::getInventoryCode,
                        Collectors.mapping(StockInventoryWarehouseTrace::getUpdatedNumAbs,
                                Collectors.reducing(0, Integer::sum))));
    }

    /**
     * 查询对应货品在指定(所有)仓库的所有业务单号链路占用库存统计数【MAP：key-货品编码，value-链路占用库存统计数】
     *
     * @param inventoryCodes
     * @param warehouseCode
     * @return
     */
    @Override
    public Map<String, Integer> getAllTracesOccupyToMap(List<String> inventoryCodes, String warehouseCode) {

        return getWarehouseTraces(null, inventoryCodes, warehouseCode, true, true)
                .stream().collect(Collectors.groupingBy(StockInventoryWarehouseTrace::getInventoryCode,
                        Collectors.mapping(StockInventoryWarehouseTrace::getUpdatedNumAbs,
                                Collectors.reducing(0, Integer::sum))));
    }

    /**
     * 查询对应货品在所有仓库的所有业务单号链路占用库存数【MAP：key-仓库编码，value-链路占用库存数】
     *
     * @param inventoryCode
     * @return
     */
    @Override
    public Map<String, Integer> getWhTracesOccupyToMap(String inventoryCode) {

        return getWarehouseTraces(null, Arrays.asList(inventoryCode), null, true, true)
                .stream().collect(Collectors.groupingBy(StockInventoryWarehouseTrace::getWarehouseCode,
                        Collectors.mapping(StockInventoryWarehouseTrace::getUpdatedNumAbs,
                                Collectors.reducing(0, Integer::sum))));
    }

    /**
     * 根号业务单号(链路号)关闭任务链路
     *
     * @param docNo 业务单号(链路号)
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updTraceDone(String docNo) {

        String now = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));

        LambdaUpdateWrapper<StockInventoryWarehouseTrace> updateWrapper = Wrappers
                .lambdaUpdate(StockInventoryWarehouseTrace.class)
                .eq(StockInventoryWarehouseTrace::getDirectSn, docNo)
                .set(StockInventoryWarehouseTrace::getInProgress, false)
                .setSql(String.format("remark = CONCAT('%s', ' 关闭任务链', ' || \n', IFNULL(remark,''))", now));

        if (!update(updateWrapper)) {
            String redisKey = RedisUtils.getRedisKey(CommonConstant.REDISSON_RW_LOCK_TRACE_DONE, docNo);
            redisSupportService.bucketSet(redisKey, now + " [Redis]", 28, TimeUnit.DAYS);
        }

        return true;
    }

}
